<?php
declare (strict_types = 1);

namespace app\controller;

use app\middleware\Auth;
use app\model\CommissionRecord;
use app\model\User;
use app\util\QrCode;
use think\Request;
use think\facade\Db;
use think\facade\Env;

/**
 * @OA\Tag(
 *     name="用户",
 *     description="用户相关接口"
 * )
 */
class UserController extends ApiBaseController
{
    /**
     * 前置中间件
     * @var array
     */
    protected $middleware = [
        Auth::class,
    ];
    
    /**
     * 获取当前用户信息
     *
     * @OA\Get(
     *     path="/api/user/info",
     *     summary="获取用户信息",
     *     description="获取当前登录用户的详细信息，包括个人资料、代理等级、邀请链接等",
     *     tags={"用户"},
     *     security={{"bearerAuth":{}}},
     *     @OA\Response(
     *         response=200,
     *         description="成功",
     *         @OA\JsonContent(
     *             @OA\Property(property="code", type="integer", example=200),
     *             @OA\Property(property="msg", type="string", example="获取成功"),
     *             @OA\Property(property="data", type="object",
     *                 @OA\Property(property="id", type="integer", example=1, description="用户ID"),
     *                 @OA\Property(property="openid", type="string", example="wx_openid_123456", description="微信OpenID"),
     *                 @OA\Property(property="nickname", type="string", example="张三", description="用户昵称"),
     *                 @OA\Property(property="avatar", type="string", example="http://example.com/avatar.jpg", description="头像URL"),
     *                 @OA\Property(property="gender", type="integer", example=1, description="性别：0-未知，1-男，2-女"),
     *                 @OA\Property(property="gender_text", type="string", example="男", description="性别文本描述"),
     *                 @OA\Property(property="city", type="string", example="广州", description="所在城市"),
     *                 @OA\Property(property="parent_id", type="integer", example=0, description="上级代理ID，0表示无上级"),
     *                 @OA\Property(property="commission", type="string", example="100.00", description="累计佣金金额"),
     *                 @OA\Property(property="team_commission", type="string", example="500.00", description="团队佣金总额"),
     *                 @OA\Property(property="team_count", type="integer", example=10, description="团队成员数量"),
     *                 @OA\Property(property="level_update_time", type="string", format="date-time", example="2023-07-15 10:00:00", description="等级更新时间"),
     *                 @OA\Property(property="status", type="integer", example=1, description="用户状态：0-禁用，1-正常"),
     *                 @OA\Property(property="create_time", type="string", format="date-time", example="2023-07-01 10:00:00", description="创建时间"),
     *                 @OA\Property(property="update_time", type="string", format="date-time", example="2023-07-15 10:00:00", description="更新时间"),
     *                 @OA\Property(property="invite_qrcode", type="string", example="https://api.example.com/uploads/qrcodes/12345.png", description="邀请二维码图片URL"),
     *             )
     *         )
     *     ),
     *     @OA\Response(
     *         response=401,
     *         description="未授权",
     *         @OA\JsonContent(
     *             @OA\Property(property="code", type="integer", example=401),
     *             @OA\Property(property="msg", type="string", example="请先登录"),
     *             @OA\Property(property="data", type="object")
     *         )
     *     )
     * )
     *
     * @return \think\Response
     */
    public function info()
    {
        // 校验登录
        $check = $this->checkLogin();
        if ($check !== true) return $check;
        
        // 获取用户数据
        $userData = $this->user->toArray();
        
        // 获取前端基础地址
        $frontendBaseUrl = Env::get('app.frontend_base_url', 'https://mh.xianxia99.com');
        
        // 生成邀请二维码URL和邀请链接
        $userData['invite_qrcode'] = \app\util\QrCode::generateInviteQrUrl($userData['id'], $frontendBaseUrl); 
        
        return $this->success($userData, '获取成功');
    }
    
    /**
     * 获取我的团队
     *
     * @OA\Get(
     *     path="/api/user/team",
     *     summary="获取我的团队信息",
     *     description="获取直接下级用户列表及团队统计信息",
     *     tags={"用户"},
     *     security={{"bearerAuth":{}}},
     *     @OA\Parameter(
     *         name="page",
     *         in="query",
     *         description="页码",
     *         required=false,
     *         @OA\Schema(type="integer", default=1)
     *     ),
     *     @OA\Parameter(
     *         name="limit",
     *         in="query",
     *         description="每页数量",
     *         required=false,
     *         @OA\Schema(type="integer", default=20)
     *     ),
     *     @OA\Response(
     *         response=200,
     *         description="获取成功",
     *         @OA\JsonContent(
     *             @OA\Property(property="code", type="integer", example=200),
     *             @OA\Property(property="msg", type="string", example="获取成功"),
     *             @OA\Property(property="data", type="object",
     *                 @OA\Property(property="list", type="array", 
     *                     @OA\Items(type="object",
     *                         @OA\Property(property="id", type="integer", example=2),
     *                         @OA\Property(property="nickname", type="string", example="团队成员1"),
     *                         @OA\Property(property="avatar", type="string", example="https://example.com/avatar1.jpg"),
     *                         @OA\Property(property="agent_level", type="integer", example=1),
     *                         @OA\Property(property="commission", type="number", format="float", example=45.67),
     *                         @OA\Property(property="create_time", type="string", format="date-time", example="2023-07-15 15:30:00")
     *                     )
     *                 ),
     *                 @OA\Property(property="team_count", type="integer", example=15),
     *                 @OA\Property(property="team_commission", type="number", format="float", example=789.12)
     *             )
     *         )
     *     ),
     *     @OA\Response(
     *         response=401,
     *         description="未授权",
     *         @OA\JsonContent(
     *             @OA\Property(property="code", type="integer", example=401),
     *             @OA\Property(property="msg", type="string", example="请先登录"),
     *             @OA\Property(property="data", type="object")
     *         )
     *     )
     * )
     *
     * @param Request $request
     * @return \think\Response
     */
    public function team(Request $request)
    {
        // 校验登录
        $check = $this->checkLogin();
        if ($check !== true) return $check;
        
        // 获取分页参数
        list($page, $limit) = $this->getPaginate();
        
        // 查询下级用户
        $users = User::where('parent_id', $this->user->id)
            ->order('create_time', 'desc')
            ->paginate([
                'list_rows' => $limit,
                'page' => $page,
            ]);
        
        // 统计团队信息
        $teamCount = User::where('parent_id', $this->user->id)->count();
        $teamCommission = $this->user->team_commission;
        
        return $this->success([
            'list' => $users,
            'team_count' => $teamCount,
            'team_commission' => $teamCommission,
        ], '获取成功');
    }
    
    /**
     * 获取佣金记录
     *
     * @OA\Get(
     *     path="/api/user/commissions",
     *     summary="获取佣金记录",
     *     description="获取当前用户的佣金收入记录列表",
     *     tags={"用户"},
     *     security={{"bearerAuth":{}}},
     *     @OA\Parameter(
     *         name="page",
     *         in="query",
     *         description="页码",
     *         required=false,
     *         @OA\Schema(type="integer", default=1)
     *     ),
     *     @OA\Parameter(
     *         name="limit",
     *         in="query",
     *         description="每页数量",
     *         required=false,
     *         @OA\Schema(type="integer", default=20)
     *     ),
     *     @OA\Response(
     *         response=200,
     *         description="获取成功",
     *         @OA\JsonContent(
     *             @OA\Property(property="code", type="integer", example=200),
     *             @OA\Property(property="msg", type="string", example="获取成功"),
     *             @OA\Property(property="data", type="object",
     *                 @OA\Property(property="list", type="array", 
     *                     @OA\Items(type="object",
     *                         @OA\Property(property="id", type="integer", example=1),
     *                         @OA\Property(property="user_id", type="integer", example=1),
     *                         @OA\Property(property="from_user_id", type="integer", example=2),
     *                         @OA\Property(property="order_id", type="string", example="202307150123456789"),
     *                         @OA\Property(property="amount", type="number", format="float", example=0.54),
     *                         @OA\Property(property="level", type="integer", example=1),
     *                         @OA\Property(property="from_level", type="integer", example=1),
     *                         @OA\Property(property="status", type="integer", example=1),
     *                         @OA\Property(property="remark", type="string", example="一级佣金"),
     *                         @OA\Property(property="create_time", type="string", format="date-time", example="2023-07-15 16:30:00"),
     *                         @OA\Property(property="from_user", type="object",
     *                             @OA\Property(property="id", type="integer", example=2),
     *                             @OA\Property(property="nickname", type="string", example="下级用户")
     *                         )
     *                     )
     *                 ),
     *                 @OA\Property(property="total_commission", type="number", format="float", example=123.45)
     *             )
     *         )
     *     ),
     *     @OA\Response(
     *         response=401,
     *         description="未授权",
     *         @OA\JsonContent(
     *             @OA\Property(property="code", type="integer", example=401),
     *             @OA\Property(property="msg", type="string", example="请先登录"),
     *             @OA\Property(property="data", type="object")
     *         )
     *     )
     * )
     *
     * @param Request $request
     * @return \think\Response
     */
    public function commissions(Request $request)
    {
        // 校验登录
        $check = $this->checkLogin();
        if ($check !== true) return $check;
        
        // 获取分页参数
        list($page, $limit) = $this->getPaginate();
        
        // 查询佣金记录
        $commissions = CommissionRecord::with(['fromUser'])
            ->where('user_id', $this->user->id)
            ->where('status', 1) // 有效记录
            ->order('create_time', 'desc')
            ->paginate([
                'list_rows' => $limit,
                'page' => $page,
            ]);
        
        // 统计佣金
        $totalCommission = $this->user->commission;
        
        return $this->success([
            'list' => $commissions,
            'total_commission' => $totalCommission,
        ], '获取成功');
    }
    
    

    /**
     * 申请提现
     *
     * @OA\Post(
     *     path="/api/user/withdraw",
     *     summary="申请提现",
     *     description="申请提现佣金到微信",
     *     tags={"用户"},
     *     security={{"bearerAuth":{}}},
     *     @OA\RequestBody(
     *         required=true,
     *         @OA\MediaType(
     *             mediaType="application/json",
     *             @OA\Schema(
     *                 required={"amount", "wechat_qrcode"},
     *                 @OA\Property(property="amount", type="number", format="float", example=100.00, description="提现金额"),
     *                 @OA\Property(property="wechat_qrcode", type="string", example="https://example.com/qrcode.jpg", description="微信收款码URL")
     *             )
     *         )
     *     ),
     *     @OA\Response(
     *         response=200,
     *         description="申请成功",
     *         @OA\JsonContent(
     *             @OA\Property(property="code", type="integer", example=200),
     *             @OA\Property(property="msg", type="string", example="提现申请提交成功，等待审核"),
     *             @OA\Property(property="data", type="object",
     *                 @OA\Property(property="id", type="integer", example=1, description="提现记录ID"),
     *                 @OA\Property(property="amount", type="number", format="float", example=100.00, description="提现金额"),
     *                 @OA\Property(property="create_time", type="string", format="date-time", example="2023-07-15 10:00:00", description="申请时间")
     *             )
     *         )
     *     ),
     *     @OA\Response(
     *         response=400,
     *         description="参数错误或余额不足",
     *         @OA\JsonContent(
     *             @OA\Property(property="code", type="integer", example=400),
     *             @OA\Property(property="msg", type="string", example="提现金额必须大于0"),
     *             @OA\Property(property="data", type="object")
     *         )
     *     ),
     *     @OA\Response(
     *         response=401,
     *         description="未授权",
     *         @OA\JsonContent(
     *             @OA\Property(property="code", type="integer", example=401),
     *             @OA\Property(property="msg", type="string", example="请先登录"),
     *             @OA\Property(property="data", type="object")
     *         )
     *     )
     * )
     *
     * @param Request $request
     * @return \think\Response
     */
    public function withdraw(Request $request)
    {
        // 校验登录
        $check = $this->checkLogin();
        if ($check !== true) return $check;
        
        try {
            // 验证参数
            $param = $request->post();
            $validate = $this->validate($param, [
                'amount' => 'require|float|gt:0',
                'wechat_qrcode' => 'require|url|max:255',
            ], [
                'amount.require' => '提现金额不能为空',
                'amount.float' => '提现金额必须是有效的金额',
                'amount.gt' => '提现金额必须大于0',
                'wechat_qrcode.require' => '微信收款码不能为空',
                'wechat_qrcode.url' => '微信收款码必须是有效的URL',
                'wechat_qrcode.max' => '微信收款码URL过长',
            ]);
            
            if ($validate !== true && is_string($validate)) {
                return $this->error($validate);
            }
            
            // 获取金额
            $amount = (float) $param['amount'];
            
            // 检查用户余额是否足够
            if ($this->user->commission < $amount) {
                return $this->error('余额不足，无法提现');
            }
            
            // 开始事务
            Db::startTrans();
            try {
                // 创建提现记录
                $withdraw = \app\model\WithdrawRecord::create([
                    'user_id' => $this->user->id,
                    'amount' => $amount,
                    'wechat_qrcode' => $param['wechat_qrcode'],
                    'status' => 0, // 待审核
                ]);
                
                if (!$withdraw) {
                    throw new \Exception('创建提现记录失败');
                }
                
                // 扣减用户余额
                $this->user->save([
                    'commission' => Db::raw('commission-' . $amount)
                ]);
                
                // 提交事务
                Db::commit();
                
                return $this->success([
                    'id' => $withdraw->id,
                    'amount' => $withdraw->amount,
                    'create_time' => $withdraw->create_time,
                ], '提现申请提交成功，等待审核');
                
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                \think\facade\Log::error('Withdraw failed: ' . $e->getMessage() . ' | Trace: ' . $e->getTraceAsString());
                throw $e;
            }
            
        } catch (\Exception $e) {
            \think\facade\Log::error('Withdraw error: ' . $e->getMessage() . ' | Trace: ' . $e->getTraceAsString());
            return $this->error('申请提现失败: ' . $e->getMessage());
        }
    }
    
    /**
     * 获取提现记录列表
     *
     * @OA\Get(
     *     path="/api/user/withdraw_records",
     *     summary="获取提现记录列表",
     *     description="获取当前用户的提现记录列表",
     *     tags={"用户"},
     *     security={{"bearerAuth":{}}},
     *     @OA\Parameter(
     *         name="page",
     *         in="query",
     *         description="页码，默认1",
     *         required=false,
     *         @OA\Schema(type="integer", default=1)
     *     ),
     *     @OA\Parameter(
     *         name="limit",
     *         in="query",
     *         description="每页记录数，默认10",
     *         required=false,
     *         @OA\Schema(type="integer", default=10)
     *     ),
     *     @OA\Response(
     *         response=200,
     *         description="获取成功",
     *         @OA\JsonContent(
     *             @OA\Property(property="code", type="integer", example=200),
     *             @OA\Property(property="msg", type="string", example="获取成功"),
     *             @OA\Property(property="data", type="object",
     *                 @OA\Property(property="total", type="integer", example=10, description="总记录数"),
     *                 @OA\Property(property="per_page", type="integer", example=10, description="每页数量"),
     *                 @OA\Property(property="current_page", type="integer", example=1, description="当前页码"),
     *                 @OA\Property(property="last_page", type="integer", example=1, description="最后一页页码"),
     *                 @OA\Property(property="data", type="array", description="提现记录列表", 
     *                     @OA\Items(type="object",
     *                         @OA\Property(property="id", type="integer", example=1, description="提现记录ID"),
     *                         @OA\Property(property="amount", type="number", format="float", example=100.00, description="提现金额"),
     *                         @OA\Property(property="status", type="integer", example=0, description="状态：0-待审核，1-已通过，2-已拒绝"),
     *                         @OA\Property(property="status_text", type="string", example="待审核", description="状态文本"),
     *                         @OA\Property(property="remark", type="string", example="审核通过", description="备注信息"),
     *                         @OA\Property(property="create_time", type="string", format="date-time", example="2023-07-15 10:00:00", description="申请时间"),
     *                         @OA\Property(property="audit_time", type="string", format="date-time", example="2023-07-15 11:00:00", description="审核时间")
     *                     )
     *                 )
     *             )
     *         )
     *     ),
     *     @OA\Response(
     *         response=401,
     *         description="未授权",
     *         @OA\JsonContent(
     *             @OA\Property(property="code", type="integer", example=401),
     *             @OA\Property(property="msg", type="string", example="请先登录"),
     *             @OA\Property(property="data", type="object")
     *         )
     *     )
     * )
     *
     * @param Request $request
     * @return \think\Response
     */
    public function withdrawRecords(Request $request)
    {
        // 校验登录
        $check = $this->checkLogin();
        if ($check !== true) return $check;
        
        try {
            // 获取分页参数
            list($page, $limit) = $this->getPaginate();
            
            // 查询提现记录
            $records = \app\model\WithdrawRecord::where('user_id', $this->user->id)
                ->order('create_time', 'desc')
                ->paginate([
                    'list_rows' => $limit,
                    'page' => $page,
                ]);
            
            // 处理数据
            $data = $records->toArray();
            if (isset($data['data']) && is_array($data['data'])) {
                foreach ($data['data'] as &$item) {
                    $item['status_text'] = $this->getWithdrawStatusText($item['status']);
                }
            }
            
            return $this->success($data, '获取成功');
            
        } catch (\Exception $e) {
            \think\facade\Log::error('Get withdraw records error: ' . $e->getMessage() . ' | Trace: ' . $e->getTraceAsString());
            return $this->error('获取提现记录失败: ' . $e->getMessage());
        }
    }
    
    /**
     * 获取提现状态文本
     * 
     * @param int $status
     * @return string
     */
    protected function getWithdrawStatusText($status)
    {
        $statuses = [
            0 => '待审核',
            1 => '已通过',
            2 => '已拒绝'
        ];
        return $statuses[$status] ?? '未知';
    }

    /**
     * 获取提现榜单
     *
     * @OA\Get(
     *     path="/api/user/withdraw_leaderboard",
     *     summary="获取提现榜单",
     *     description="获取用户提现排行榜，可按时间段筛选",
     *     tags={"用户"},
     *     security={{"bearerAuth":{}}},
     *     @OA\Parameter(
     *         name="time_range",
     *         in="query",
     *         description="时间范围：today(今日)、yesterday(昨天)、month(本月)、last_month(上月)、all(全部，默认)",
     *         required=false,
     *         @OA\Schema(type="string", enum={"today", "yesterday", "month", "last_month", "all"})
     *     ),
     *     @OA\Parameter(
     *         name="limit",
     *         in="query",
     *         description="返回记录数量限制",
     *         required=false,
     *         @OA\Schema(type="integer", default=20)
     *     ),
     *     @OA\Response(
     *         response=200,
     *         description="成功",
     *         @OA\JsonContent(
     *             type="object",
     *             @OA\Property(property="code", type="integer", example=200),
     *             @OA\Property(property="msg", type="string", example="获取成功"),
     *             @OA\Property(
     *                 property="data",
     *                 type="array",
     *                 @OA\Items(
     *                     type="object",
     *                     @OA\Property(property="user_id", type="integer", example=1),
     *                     @OA\Property(property="nickname", type="string", example="张三"),
     *                     @OA\Property(property="agent_level", type="integer", example=2),
     *                     @OA\Property(property="agent_level_text", type="string", example="V2"),
     *                     @OA\Property(property="avatar", type="string", example="http://example.com/avatar.jpg"),
     *                     @OA\Property(property="total_amount", type="string", example="1234.56")
     *                 )
     *             )
     *         )
     *     )
     * )
     */
    public function withdrawLeaderboard(Request $request)
    {
        try {
            // 获取limit参数，默认20条
            $limit = (int) $request->param('limit', 20);
            
            // 获取时间范围参数
            $timeRange = $request->param('time_range', 'all');
            
            // 查询提现成功的记录，按用户分组并计算总金额
            $query = Db::name('withdraw_records')
                ->alias('w')
                ->join('users u', 'w.user_id = u.id')
                ->where('w.status', 1); // 只统计审核通过的提现
                
            // 根据时间范围参数添加时间条件
            switch ($timeRange) {
                case 'today':
                    // 今日
                    $query->whereTime('w.create_time', 'today');
                    break;
                case 'yesterday':
                    // 昨天
                    $query->whereTime('w.create_time', 'yesterday');
                    break;
                case 'month':
                    // 本月
                    $query->whereTime('w.create_time', 'month');
                    break;
                case 'last_month':
                    // 上月
                    $startTime = date('Y-m-01 00:00:00', strtotime('-1 month'));
                    $endTime = date('Y-m-01 00:00:00');
                    $query->whereBetweenTime('w.create_time', $startTime, $endTime);
                    break;
                case 'all':
                default:
                    // 全部时间，不添加时间限制
                    break;
            }
            
            // 完成查询条件设置
            $query->field([
                    'w.user_id',
                    'u.nickname',
                    'u.agent_level',
                    'u.avatar',
                    'SUM(w.amount) as total_amount'
                ])
                ->group('w.user_id')
                ->order('total_amount', 'desc')
                ->limit($limit);
                
            // 执行查询
            $leaderboardData = $query->select();
            
            // 格式化金额
            $leaderboard = $leaderboardData->each(function($item) {
                    $item['total_amount'] = number_format((float)$item['total_amount'], 2, '.', '');
                    // 添加等级文本
                    $item['agent_level_text'] = 'V' . $item['agent_level'];
                    return $item;
                });
            
            return $this->success($leaderboard, '获取成功');
            
        } catch (\Exception $e) {
            \think\facade\Log::error('获取提现榜单失败: ' . $e->getMessage() . ' | Trace: ' . $e->getTraceAsString());
            return $this->error('获取提现榜单失败: ' . $e->getMessage());
        }
    }
    
    /**
     * @OA\Get(
     *     path="/api/user/recent_box_orders",
     *     summary="获取最近打开的盲盒订单",
     *     description="获取最近打开的盲盒订单信息，包含用户信息和抽取的纸条统计",
     *     tags={"用户"},
     *     @OA\Parameter(
     *         name="limit",
     *         in="query",
     *         description="返回记录数量限制",
     *         required=false,
     *         @OA\Schema(type="integer", default=10)
     *     ),
     *     @OA\Response(
     *         response=200,
     *         description="成功",
     *         @OA\JsonContent(
     *             @OA\Property(property="code", type="integer", example=200),
     *             @OA\Property(property="msg", type="string", example="获取成功"),
     *             @OA\Property(property="data", type="array", 
     *                 @OA\Items(
     *                     @OA\Property(property="order_id", type="string", example="202307150001"),
     *                     @OA\Property(property="user_id", type="integer", example=1),
     *                     @OA\Property(property="nickname", type="string", example="张三"),
     *                     @OA\Property(property="avatar", type="string", example="http://example.com/avatar.jpg"),
     *                     @OA\Property(property="draw_count", type="integer", example=5, description="抽取的纸条数量"),
     *                     @OA\Property(property="gender", type="integer", example=1, description="性别: 1-男, 2-女"),
     *                     @OA\Property(property="gender_text", type="string", example="男", description="性别文本"),
     *                     @OA\Property(property="pay_time", type="string", format="date-time", example="2023-07-15 10:00:00")
     *                 )
     *             )
     *         )
     *     )
     * )
     */
    public function recentBoxOrders(Request $request)
    {
        try {
            // 获取limit参数，默认10条
            $limit = (int) $request->param('limit', 10);
            
            // 查询最近成功支付的订单
            $orders = \app\model\NoteDraw::with('user')
                ->where('status', 1) // 已支付
                ->order('pay_time', 'desc')
                ->limit($limit)
                ->select();
            
            $result = [];
            foreach ($orders as $order) {
                // 获取性别信息
                $gender = 0; // 默认未知性别
                $drawCount = 0; // 默认抽取数量为0
                
                if ($order->draw_type == 1) {
                    // 单抽
                    $note = \app\model\Note::find($order->note_id);
                    $drawCount = 1;
                    $gender = $note ? $note->gender : 0;
                } else {
                    // 多抽 - 因为抽取的纸条性别相同，只需要获取第一条的性别即可
                    $noteItem = \app\model\NoteDrawItem::where('draw_id', $order->id)->find();
                    if ($noteItem) {
                        $note = \app\model\Note::find($noteItem->note_id);
                        $gender = $note ? $note->gender : 0;
                    }
                    
                    // 计算抽取数量
                    $drawCount = \app\model\NoteDrawItem::where('draw_id', $order->id)->count();
                }
                
                // 获取性别文本
                $genderText = '未知';
                if ($gender == 1) {
                    $genderText = '男';
                } else if ($gender == 2) {
                    $genderText = '女';
                }
                
                // 组装数据
                $result[] = [
                    'order_id' => $order->order_id,
                    'user_id' => $order->user_id,
                    'nickname' => $order->user ? $order->user->nickname : '未知用户',
                    'avatar' => $order->user ? $order->user->avatar : '',
                    'draw_count' => $drawCount,
                    'gender' => $gender,
                    'gender_text' => $genderText,
                ];
            }
            
            return $this->success($result, '获取成功');
            
        } catch (\Exception $e) {
            \think\facade\Log::error('获取最近盲盒订单失败: ' . $e->getMessage() . ' | Trace: ' . $e->getTraceAsString());
            return $this->error('获取最近盲盒订单失败: ' . $e->getMessage());
        }
    }
    
    /**
     * @OA\Get(
     *     path="/api/user/upgrade_conditions",
     *     summary="获取代理升级条件",
     *     description="获取V1、V2、V3代理的升级条件和特权说明",
     *     tags={"用户"},
     *     @OA\Response(
     *         response=200,
     *         description="成功",
     *         @OA\JsonContent(
     *             @OA\Property(property="code", type="integer", example=200),
     *             @OA\Property(property="msg", type="string", example="获取成功"),
     *             @OA\Property(property="data", type="object",
     *                 @OA\Property(property="v1", type="object",
     *                     @OA\Property(property="level", type="integer", example=1),
     *                     @OA\Property(property="name", type="string", example="V1"),
     *                     @OA\Property(property="current", type="boolean", example=true),
     *                     @OA\Property(property="privileges", type="array", @OA\Items(type="string")),
     *                     @OA\Property(property="commission_rates", type="object",
     *                         @OA\Property(property="direct", type="string", example="52%"),
     *                         @OA\Property(property="team", type="string", example="2%")
     *                     )
     *                 ),
     *                 @OA\Property(property="v2", type="object",
     *                     @OA\Property(property="level", type="integer", example=2),
     *                     @OA\Property(property="name", type="string", example="V2"),
     *                     @OA\Property(property="current", type="boolean", example=false),
     *                     @OA\Property(property="upgrade_conditions", type="array", @OA\Items(type="object",
     *                         @OA\Property(property="type", type="string", example="personal"),
     *                         @OA\Property(property="title", type="string", example="个人任务"),
     *                         @OA\Property(property="description", type="string", example="个人佣金结算达到5000元"),
     *                         @OA\Property(property="target", type="number", example=5000),
     *                         @OA\Property(property="current", type="number", example=2500),
     *                         @OA\Property(property="progress", type="number", example=50),
     *                         @OA\Property(property="completed", type="boolean", example=false)
     *                     )),
     *                     @OA\Property(property="privileges", type="array", @OA\Items(type="string")),
     *                     @OA\Property(property="commission_rates", type="object",
     *                         @OA\Property(property="direct", type="string", example="63%"),
     *                         @OA\Property(property="indirect", type="string", example="9%"),
     *                         @OA\Property(property="same_level", type="string", example="4%")
     *                     )
     *                 ),
     *                 @OA\Property(property="v3", type="object",
     *                     @OA\Property(property="level", type="integer", example=3),
     *                     @OA\Property(property="name", type="string", example="V3"),
     *                     @OA\Property(property="current", type="boolean", example=false),
     *                     @OA\Property(property="upgrade_conditions", type="array", @OA\Items(type="object",
     *                         @OA\Property(property="type", type="string", example="team"),
     *                         @OA\Property(property="title", type="string", example="团队任务"),
     *                         @OA\Property(property="description", type="string", example="团队总佣金结算达到18000元"),
     *                         @OA\Property(property="target", type="number", example=18000),
     *                         @OA\Property(property="current", type="number", example=5000),
     *                         @OA\Property(property="progress", type="number", example=27.78),
     *                         @OA\Property(property="completed", type="boolean", example=false)
     *                     )),
     *                     @OA\Property(property="privileges", type="array", @OA\Items(type="string")),
     *                     @OA\Property(property="commission_rates", type="object",
     *                         @OA\Property(property="direct", type="string", example="73%"),
     *                         @OA\Property(property="v1_direct", type="string", example="21%"),
     *                         @OA\Property(property="v1_indirect", type="string", example="19%"),
     *                         @OA\Property(property="v2_direct", type="string", example="10%"),
     *                         @OA\Property(property="same_level", type="string", example="2%")
     *                     )
     *                 )
     *             )
     *         )
     *     )
     * )
     */
    public function upgradeConditions()
    {
        // 校验登录
        $check = $this->checkLogin();
        if ($check !== true) return $check;
        
        try {
            // 获取系统设置
            $settings = \app\model\SystemSetting::getSettings();
            
            // 获取当前用户信息
            $user = $this->user;
            $currentLevel = $user->agent_level ?? 1;
            
            // V1特权描述
            $v1Privileges = [
                "直推52%消费提成",
                "间推2%消费提成"
            ];
            
            // V2特权描述
            $v2Privileges = [
                "直推63%消费提成",
                "一代V1间推9%消费提成（无极限）",
                "同级V2直推4%消费提成",
                "同级V2间推2%消费提成"
            ];
            
            // V3特权描述
            $v3Privileges = [
                "直推73%消费提成",
                "一代V1间推21%消费提成",
                "二代V1间推19%消费提成（无极限）",
                "一代V2直推10%消费提成",
                "V2二代V1间推10%消费提成（无极限）",
                "同级V3直推2%消费提成",
                "同级V3间推1%消费提成",
                "三代无提成"
            ];
            
            // 构建升级条件数据
            $result = [
                'v1' => [
                    'level' => 1,
                    'name' => 'V1',
                    'current' => $currentLevel == 1,
                    'privileges' => $v1Privileges,
                    'commission_rates' => [
                        'direct' => '52%',
                        'team' => '2%'
                    ]
                ],
                'v2' => [
                    'level' => 2,
                    'name' => 'V2',
                    'current' => $currentLevel == 2,
                    'privileges' => $v2Privileges,
                    'commission_rates' => [
                        'direct' => '63%',
                        'indirect' => '9%',
                        'same_level' => '4%'
                    ]
                ],
                'v3' => [
                    'level' => 3,
                    'name' => 'V3',
                    'current' => $currentLevel == 3,
                    'privileges' => $v3Privileges,
                    'commission_rates' => [
                        'direct' => '73%',
                        'v1_direct' => '21%',
                        'v1_indirect' => '19%',
                        'v2_direct' => '10%',
                        'same_level' => '2%'
                    ]
                ]
            ];
            
            // 如果不是最高级别，添加升级条件
            if ($currentLevel < 3) {
                $nextLevel = $currentLevel + 1;
                
                if ($nextLevel == 2) {
                    // 升级到V2的条件
                    $teamCountTarget = floatval($settings['v2_upgrade_team_count'] ?? 15);
                    $teamCommissionTarget = floatval($settings['v2_upgrade_team_commission'] ?? 500);
                    $personalCommissionTarget = floatval($settings['v2_upgrade_personal_commission'] ?? 5000);
                    $minCommission = floatval($settings['v2_upgrade_min_commission'] ?? 10);
                    
                    // 计算团队佣金大于10元的人数
                    $teamCommissionCount = \app\model\CommissionRecord::alias('cr')
                        ->join('users u', 'cr.from_user_id = u.id')
                        ->where('u.parent_id', $user->id)
                        ->where('cr.amount', '>', $minCommission)
                        ->count();
                        
                    $teamCommission = $user->team_commission;
                    $personalCommission = $user->commission;
                    
                    // 计算进度百分比
                    $teamCountProgress = min(100, round(($teamCommissionCount / $teamCountTarget) * 100, 2));
                    $teamCommissionProgress = min(100, round(($teamCommission / $teamCommissionTarget) * 100, 2));
                    $personalCommissionProgress = min(100, round(($personalCommission / $personalCommissionTarget) * 100, 2));
                    
                    // 添加升级条件
                    $result['v2']['upgrade_conditions'] = [
                        [
                            'type' => 'team_count',
                            'title' => '团队任务1',
                            'description' => "团队中{$teamCountTarget}个下级佣金大于{$minCommission}元",
                            'target' => $teamCountTarget,
                            'current' => $teamCommissionCount,
                            'progress' => $teamCountProgress,
                            'completed' => $teamCommissionCount >= $teamCountTarget
                        ],
                        [
                            'type' => 'team_commission',
                            'title' => '团队任务2',
                            'description' => "团队总佣金结算达到{$teamCommissionTarget}元",
                            'target' => $teamCommissionTarget,
                            'current' => $teamCommission,
                            'progress' => $teamCommissionProgress,
                            'completed' => $teamCommission >= $teamCommissionTarget
                        ],
                        [
                            'type' => 'personal',
                            'title' => '个人任务',
                            'description' => "个人佣金结算达到{$personalCommissionTarget}元",
                            'target' => $personalCommissionTarget,
                            'current' => $personalCommission,
                            'progress' => $personalCommissionProgress,
                            'completed' => $personalCommission >= $personalCommissionTarget
                        ]
                    ];
                } else if ($nextLevel == 3) {
                    // 升级到V3的条件
                    $teamCountTarget = floatval($settings['v3_upgrade_team_count'] ?? 180);
                    $teamCommissionTarget = floatval($settings['v3_upgrade_team_commission'] ?? 18000);
                    $personalCommissionTarget = floatval($settings['v3_upgrade_personal_commission'] ?? 25000);
                    $minCommission = floatval($settings['v3_upgrade_min_commission'] ?? 10);
                    
                    // 计算团队佣金大于10元的人数
                    $teamCommissionCount = \app\model\CommissionRecord::alias('cr')
                        ->join('users u', 'cr.from_user_id = u.id')
                        ->where('u.parent_id', $user->id)
                        ->where('cr.amount', '>', $minCommission)
                        ->count();
                        
                    $teamCommission = $user->team_commission;
                    $personalCommission = $user->commission;
                    
                    // 计算进度百分比
                    $teamCountProgress = min(100, round(($teamCommissionCount / $teamCountTarget) * 100, 2));
                    $teamCommissionProgress = min(100, round(($teamCommission / $teamCommissionTarget) * 100, 2));
                    $personalCommissionProgress = min(100, round(($personalCommission / $personalCommissionTarget) * 100, 2));
                    
                    // 添加升级条件
                    $result['v3']['upgrade_conditions'] = [
                        [
                            'type' => 'team_count',
                            'title' => '团队任务1',
                            'description' => "团队中{$teamCountTarget}个下级佣金大于{$minCommission}元",
                            'target' => $teamCountTarget,
                            'current' => $teamCommissionCount,
                            'progress' => $teamCountProgress,
                            'completed' => $teamCommissionCount >= $teamCountTarget
                        ],
                        [
                            'type' => 'team_commission',
                            'title' => '团队任务2',
                            'description' => "团队总佣金结算达到{$teamCommissionTarget}元",
                            'target' => $teamCommissionTarget,
                            'current' => $teamCommission,
                            'progress' => $teamCommissionProgress,
                            'completed' => $teamCommission >= $teamCommissionTarget
                        ],
                        [
                            'type' => 'personal',
                            'title' => '个人任务',
                            'description' => "个人佣金结算达到{$personalCommissionTarget}元",
                            'target' => $personalCommissionTarget,
                            'current' => $personalCommission,
                            'progress' => $personalCommissionProgress,
                            'completed' => $personalCommission >= $personalCommissionTarget
                        ]
                    ];
                }
            }
            
            // 添加特殊说明
            $result['note'] = '满足任一条件即可升级';
            
            return $this->success($result, '获取升级条件成功');
        } catch (\Exception $e) {
            \think\facade\Log::error('获取升级条件失败: ' . $e->getMessage() . ' | Trace: ' . $e->getTraceAsString());
            return $this->error('获取升级条件失败: ' . $e->getMessage());
        }
    }
} 